package com.hyfrogx.modules.job.utils;

import cn.hutool.core.thread.ThreadUtil;
import com.hyfrogx.modules.job.entity.HyAdJobEntity;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * @version 1.0.0
 * @Author: lfh
 * @Date: 2019/10/18 14:55
 * @Company 汉咏科技
 */
@Slf4j
public class HyAdJob extends QuartzJobBean {
    private ExecutorService service = ThreadUtil.newSingleExecutor();

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        //获取JobDate中JobMap里的实体类参数
        HyAdJobEntity hyAdJobEntity = (HyAdJobEntity) jobExecutionContext.getMergedJobDataMap()
                .get(HyAdJobUtils.JOB_PARAM_KEY);
        // 任务开始时间
        long startTime = System.currentTimeMillis();
        try {
            // 执行任务
            log.info("任务准备执行，任务ID：" + hyAdJobEntity.getJobId());
            ScheduleRunnable task = new ScheduleRunnable(hyAdJobEntity.getBeanName(),
                    hyAdJobEntity.getMethodName(), hyAdJobEntity.getParams());
            Future<?> future = service.submit(task);

            future.get();

            // 任务执行总时长
            long times = System.currentTimeMillis() - startTime;

            log.info("任务执行完毕，任务ID：" + hyAdJobEntity.getJobId() + "  总共耗时：" + times + "毫秒");
        } catch (Exception e) {
            log.error("任务执行失败，任务ID：" + hyAdJobEntity.getJobId(), e);

            // 任务执行总时长
            long times = System.currentTimeMillis() - startTime;
        }
    }
}
